package de.trebings.gia.util;

import java.util.List;

import javax.jdo.PersistenceManager;
import javax.servlet.http.HttpSession;

import com.restfb.DefaultFacebookClient;
import com.restfb.FacebookClient;

import de.trebings.gia.entities.Password;
import de.trebings.gia.entities.User;

public class UserManager {
	PersistenceManager pm;
	HttpSession session;
	User authorizedUser;

	public UserManager(PersistenceManager pm, HttpSession session) {
		this.pm = pm;
		this.session = session;
	}

	@SuppressWarnings("unchecked")
	public List<User> getUsers() {
		String query = "select from " + User.class.getName();
		List<User> users = (List<User>) pm.newQuery(query).execute();
		return users;
	}

	public User getAuthorizedUser() {
		long userId = (Long) session.getAttribute("authenticatedUserId");
		return getUserById(userId);
	}

	@SuppressWarnings("unchecked")
	public User getUserByEmail(String email) {
		User resultUser = null;

		String query = "select from " + User.class.getName()
				+ " where email == '" + email + "'";
		List<User> users = (List<User>) pm.newQuery(query).execute();
		for (User user : users) {
			resultUser = user;
		}

		return resultUser;
	}

	@SuppressWarnings("unchecked")
	public User getUserByFbId(String fbId) {
		User resultUser = null;

		String query = "select from " + User.class.getName()
				+ " where fbId == '" + fbId + "'";
		List<User> users = (List<User>) pm.newQuery(query).execute();
		for (User user : users) {
			resultUser = user;
		}

		return resultUser;
	}

	public void addUser(String email) {
		User user = new User();
		user.setEmail(email);
		user.setStatus(User.NOT_AUTHORIZED);

		pm.makePersistent(user);
	}

	@SuppressWarnings("unchecked")
	public User getUserById(Long userId) {
		if (userId == null)
			return null;

		User resultUser = null;

		String query = "select from " + User.class.getName() + " where id == "
				+ userId;
		List<User> users = (List<User>) pm.newQuery(query).execute();
		for (User user : users) {
			resultUser = user;
		}

		return resultUser;
	}

	public boolean isAuthorized() {
		// check whether this session is already authorized
		if (session.getAttribute("authenticatedUserId") != null) {
			return true;
		} else {
			return false;
		}
	}

	public boolean authorizeViaFacebook(String accessToken) {
		boolean result = false;

		// try to authorize via facebook
		FacebookClient facebookClient = new DefaultFacebookClient(accessToken);
		com.restfb.types.User fbUser = facebookClient.fetchObject("me",
				com.restfb.types.User.class);

		de.trebings.gia.entities.User user = getUserByEmail(fbUser.getEmail());
		if (user == null) {
			user = getUserByFbId(fbUser.getId());
		}
		if (user == null) {
			addUser(fbUser.getEmail());
			System.out.println("new user created: " + fbUser.getEmail());
			authorizedUser = null;
		} else {
			if (user.getStatus() == de.trebings.gia.entities.User.AUTHORIZED) {
				result = true;
				// if(user.getName() == null || user.getName() == ""){
				user.setName(fbUser.getName());
				user.setFirstName(fbUser.getFirstName());
				user.setLastName(fbUser.getLastName());
				user.setEmail(fbUser.getEmail());
				user.setFbId(fbUser.getId());
				// }
				authenticationPostProcessing(user);
			} else {
				authorizedUser = null;
				// if ("christian.trebing@gmx.de".equals(fbUser.getEmail())) {
				// user.setStatus(de.trebings.gia.User.AUTHORIZED);
				// result = true;
				// }
			}
		}

		return result;

	}

	public boolean authorizeViaEmail(String email, String userPassword) {
		String correctPassword = getCorrectPassword();

		// if no password is defined, logon is not possible!
		if ("".equals(correctPassword)) {
			return false;
		}

		if (correctPassword.equals(userPassword)) {
			de.trebings.gia.entities.User user = getUserByEmail(email);
			if (user == null) {
				addUser(email);
				System.out.println("new user created: " + email);
				user = getUserByEmail(email);
			}
			authenticationPostProcessing(user);
			return true;
		} else {
			return false;
		}
	}

	private void authenticationPostProcessing(de.trebings.gia.entities.User user) {
		authorizedUser = user;
		session.setAttribute("authenticatedUserId", user.getId());
		user.updateLoginDate();
	}

	@SuppressWarnings("unchecked")
	private String getCorrectPassword() {
		String query = "select from " + Password.class.getName();
		List<Password> passwords = (List<Password>) pm.newQuery(query)
				.execute();
		if (passwords.size() == 1) {
			return passwords.get(0).getPassword();
		} else {
			return "";
		}
	}

}
